import axios, { InternalAxiosRequestConfig, AxiosResponse } from "axios";
import { getJWTToken, setJWTToken } from "~/request/utils";
import userStore from "~/store/user";
import router from "~/router/index";
export const baseURL = "http://localhost:8888";
const fetch = axios.create({
  baseURL,
  timeout: 10000,
});

fetch.interceptors.request.use((config: InternalAxiosRequestConfig) => {
  const userStr = userStore();
  const localToken = getJWTToken();
  config.headers.Authorization = localToken ? localToken : userStr.token;
  // console.log(config)
  return config;
});
fetch.interceptors.response.use(
  (res: AxiosResponse) => {
    if (res.data.code === 1000) {
      return res.data;
    } else if (res.data.code === 1007) {
      setJWTToken("");
      router.push("/main/home");
      return new Error("登录失效");
    } else {
      window.NMessage.warning(JSON.stringify(res.data.result));
      return new Error(res.data.message);
    }
  },
  (err) => {
    window.NMessage.warning(err);
  }
);
export default fetch;
